var app = getApp();
var ajax = require('./ajax.js');

var isExtInited = false;

//初始化app
function initApp(options) {

  var {
    extSuc,
    loginSuc
  } = options || {};
    initExtConfig(function() {
        extSuc && extSuc();

        quietLogin(function() {
            loginSuc && loginSuc();
        });
    });
}

//初始化配置信息
function initExtConfig(cb) {
    var sysInfo = wx.getSystemInfoSync()

    console.log(sysInfo.windowWidth);
    app.setWinHei(sysInfo.windowHeight);
    app.setWinWid(sysInfo.windowWidth);
    if (isExtInited) {
        return cb && cb();
    }
    wx.getExtConfig && wx.getExtConfig({
        success: function(res) {
            var {
                host,
                alias,
                tabBar
            } = res.extConfig;

            isExtInited = true;
            if (host) {
                app.setHost(host);
            }
            if (alias) {
                app.setAlias(alias);
            }
            if (tabBar) {
                app.config.tabBar = tabBar;
            }
            cb && cb();
        }
    });
}

/**
 * 静默登陆
 */
function quietLogin(cb) {
    //检验登录态是否过期
    wx.checkSession({
        success: function() { //session没有过期
            if (app.getOpenId() || app.getUserSid()) {
                cb && cb();
                return;
            }
            doLogin(cb);
        },
        fail: function() { //session已过期
            doLogin(cb);
        }
    });
}

function doLogin(cb) {
    wx.login({
        success: function(res) {

            app.getUserInfo(function(userInfo) {
                var params = {
                    jscode: res.code,
                };

                if (userInfo) {
                    params.nickName = userInfo.nickName;
                    params.avatarUrl = userInfo.avatarUrl;
                }

                ajax.P('/openapi/CHome/newLogin', params, function(res) {
                    var data = res.result;
                    var appType = data.app_type;
                    var openid = data.openid;
                    var sid = data.sid;
                    var userSid = data.userSid;
                    var isPay = data.isPay;
                    var is_fenxiao = data.is_fenxiao;
                    var user_id = data.user_id;
                    var techId = data.tech_id;
                    var shop = {
                        name: data.title,
                        phone: data.contact,
                        address: data.address,
                        time: data.hours,
                        logo: data.logo,
                        shopImg: data.shop_img,
                        weixin: data.weixin,
                        qq: data.qq,
                        shareTitle: data.share_title,
                        kfState: data.kf_state,
                        isDc: data.isDc, //是否是点餐版
                    };

                    app.globalData.sid = sid || '';
                    if (openid) {
                        app.setOpenId(openid);
                    }
                    if (userSid) {
                        app.setUserSid(userSid);
                    }
                    if (is_fenxiao) {
                        app.setIsFenxiao(is_fenxiao);
                    }
                    if (user_id) {
                        app.setUserId(user_id);
                    }
                    app.setCanPay(isPay);
                    app.setShop(shop);
                    if (techId && techId != 0) {
                        app.globalData.techId = techId;
                    }
                    if (data.copyright) {
                        app.globalData.copyright = data.copyright;
                    }

                    app.globalData.modList = data.module_list || []; //功能模块
                    app.globalData.fxNeedCheck = data.fenxiao_need_check;
                    app.globalData.appType = appType;

                    cb && cb();
                });

            });
        },
        fail: function() {},
        complete: function() {}
    });
}

function jump(evt) {
    var formId = evt.detail.formId;
    var {
        openType,
        url,
        mustLogin
    } = evt.currentTarget.dataset
    var isLogin = !!app.getUserSid();

    if (mustLogin && !isLogin) {
        wx.navigateTo({
            url: '/pages/login/login'
        });
        return;
    }

    if (openType == 'navigate' || !openType) {
        openType = 'navigateTo';
    }

    wx[openType]({
        url
    });
    submitForm(formId);
}

//提交表单id
function submitForm(formId) {
    console.log('--------formId', formId);
    if (!formId) {
        return;
    }
    ajax.P('/openapi/CUser/addFormId', {
        openId: app.getOpenId(),
        formId,
    }, function(res) {});
}
//提交支付id
function submitPrepay(prepayId) {
    console.log('~~~~~~~~~prepayId', prepayId);
    if (!prepayId) {
        return
    }
    ajax.P('/openapi/CUser/addPrePayId', {
        openId: app.getOpenId(),
        prepayId,
    }, function(res) {});
}

const pageMedhods = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onPageScroll'];

function extend(Child, Parent) {　　　　
    var F = function() {};　　　　
    F.prototype = Parent.prototype;　　　　
    Child.prototype = new F();
    Child.prototype.constructor = Child;　　　　
    Child.uber = Parent.prototype;
}

//合并两个Page对象
function extendPage(source, obj) {
    if (!source || !obj) {
        return;
    }
    var newObj = {};
    var newData = {};

    Object.assign(newData, source['data']);
    Object.assign(newData, obj['data']);

    Object.assign(newObj, source);
    Object.assign(newObj, obj);

    newObj['data'] = newData;

    pageMedhods.forEach(function(methodName) {
        var sourceFunc = source[methodName];
        var objFunc = obj[methodName];

        if (sourceFunc && objFunc) {
            newObj[methodName] = function(...params) {
                sourceFunc.bind(this)(...params);
                objFunc.bind(this)(...params);
            }
        }
    });

    return newObj;
}

var pageIndex = 0;
var pageList = ['/pages/mPage1/index', '/pages/mPage2/index', '/pages/mPage3/index'];

//跳转到某个自定义页面
function goToPage(pageId) {
    console.log('-----goToPage', pageIndex);
    if (!pageId) {
        return;
    }
    var openType = 'navigateTo';
    var maxIndex = pageList.length - 1;
    var tabBar = app.config.tabBar;
    var toBarName;

    if (pageIndex > maxIndex) {
        openType = 'redirectTo';
    }

    if (tabBar) {
        Object.keys(tabBar).some(function(key) {
            if (tabBar[key] == pageId) {
                openType = 'switchTab';
                toBarName = key;
                return true;
            }
        });
    }

    if (openType == 'switchTab') {
        wx[openType]({
            url: '/pages/' + toBarName + '/index'
        });
        pageIndex = 0;
    } else {
        wx[openType]({
            url: pageList[pageIndex > maxIndex ? maxIndex : pageIndex] + '?pageId=' + pageId
        });
        pageIndex++;
    }
}

function goBackPage() {
    pageIndex--;
    console.log('-----goBackPage', pageIndex);
}
module.exports = {
    initApp,
    quietLogin,
    submitForm,
    jump,
    extend,
    extendPage,
    goToPage,
    goBackPage,
    submitPrepay
};